﻿using System;
using BizTalkFlow.Model;
using BizTalkFlow.Render;
using System.Xml.Linq;
using System.Xml;
using System.ServiceModel.Web;
using System.IO;
using System.Globalization;
using System.Web.Hosting;
using System.ServiceModel;
using System.Runtime.Serialization.Formatters;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;

namespace BizTalkFlow.WcfService
{
    public class ArtefactsLinksService : IArtefactsLinksService
    {
        private string temmplateFilename = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, Properties.Settings.Default.DgmlTempltePath);

        public ArtefactModel GetFromTo(string strStartDate, string strEndDate)
        {
            var startDate = DateTime.ParseExact(strStartDate, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
            var endDate = DateTime.ParseExact(strEndDate, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);

            return ArtefactModel.Load(startDate, endDate, true, false);
        }
        public XmlDocument GetDGMLFromTo(string strStartDate, string strEndDate)
        {
            var artefactsLinks = GetFromTo(strStartDate, strEndDate);
            var fileName = string.Format("From_{0}_To_{1}.dgml", strStartDate, strEndDate);
            SetResponseAttributs(fileName);

            var render = new DgmlRender();
            return render.RenderAsXmlDocument(temmplateFilename, artefactsLinks, false, false, false);
        }

        public ArtefactModel GetLast(string strNumberOfIntervalInPast, string strIntervalType, string strIncludeFlowInstances)
        {
            //try
            //{
            //throw new Exception("test");
            var numberOfIntervalInPast = int.Parse(strNumberOfIntervalInPast);
            var intervalType = (ArtefactModel.DateInterval)Enum.Parse(typeof(ArtefactModel.DateInterval), strIntervalType);
            var includeFlowInstances = bool.Parse(strIncludeFlowInstances);

            return ArtefactModel.Load(numberOfIntervalInPast, intervalType, true, includeFlowInstances);
            //}
            //catch (Exception ex)
            //{
            //TODO Generate Json error

            //throw new WebFaultException<Exception>(ex,System.Net.HttpStatusCode.BadRequest);
            //throw new WebFaultException(System.Net.HttpStatusCode.ServiceUnavailable);
            //throw new  FaultException(ex.ToString());
            //throw MessageFault.CreateFault(FaultCode.CreateSenderFaultCode("test", "http://technip"), ex.Message);
            //var fault = new SoapFault("CODE",ex.Message,ex.Source,new ServerFault("WebService",ex.Message,ex.StackTrace));
            //var fault = new JsonFaultDetail();
            //fault.ExceptionDetail = new ExceptionDetail(ex);
            //return fault;
            //}
        }

        public XmlDocument GetDGMLLast(string strNumberOfIntervalInPast, string strIntervalType, string strCreateApplications, string strCreateFlows, string strIncludeFlowInstances)
        {
            var createApplications = bool.Parse(strCreateApplications);
            var createFlows = bool.Parse(strCreateFlows);
            var includeFlowInstances = bool.Parse(strIncludeFlowInstances);

            var artefactsLinks = GetLast(strNumberOfIntervalInPast, strIntervalType, strIncludeFlowInstances);

            var fileName = string.Format("Last_{0}_{1}_{2}.dgml", strNumberOfIntervalInPast, strIntervalType, DateTime.Now.ToString("yyyyMMdd_HHMMss"));
            SetResponseAttributs(fileName);

            var dgmlRender = new DgmlRender();
            return dgmlRender.RenderAsXmlDocument(temmplateFilename, artefactsLinks, createApplications, createFlows, includeFlowInstances);
        }

        public ArtefactModel GetByInstanceID(string strInstanceID)
        {
            var instanceID = Guid.Parse(strInstanceID);
            return ArtefactModel.Load(instanceID, true, true);
        }
        public XmlDocument GetDGMLByInstanceID(string strInstanceID)
        {
            var artefactsLinks = GetByInstanceID(strInstanceID);
            var fileName = string.Format("InstanceID_{0}.dgml", strInstanceID);
            var render = new DgmlRender();

            SetResponseAttributs(fileName);
            return render.RenderAsXmlDocument(temmplateFilename, artefactsLinks, false, false, true);
        }

        private static void SetResponseAttributs(string fileName)
        {
            var response = WebOperationContext.Current.OutgoingResponse;
            response.ContentType = "application/dgml";
            response.Headers.Add("content-disposition", @"attachment;filename=" + fileName + "");
        }
    }
}
